package com.jeffgalper.feather;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FeatheredFileChannel extends AbstractFeathered {

  private short mFilenameSize;
  private String mFilename;
  private long mSize;

  public FeatheredFileChannel(FileChannel fc) {
    super(fc);
  }

  public File unfeather() throws IOException {
    readInfo();

    File file = new File(mFilename);
    FileOutputStream out = null;
    FileChannel fc = null;
    try {
      out = new FileOutputStream(file);
      fc = out.getChannel();
      int bytesTransferred = 0;
      while (bytesTransferred < mSize) {
        bytesTransferred += mFC.transferTo(bytesTransferred, mSize
            - bytesTransferred, fc);
      }
    } finally {
      if (fc != null)
        fc.close();
      if (out != null)
        out.close();
    }
    return file;
  }

  private void readInfo() throws IOException {
    skipHeader();
    mFilenameSize = readFilenameSize();
    mFilename = readFilename(mFilenameSize);
    mSize = readSize();
  }
}
